package level.editor.view.action.file;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import level.editor.control.main.Main;
import level.editor.control.main.MainScroll;
import level.editor.control.main.MainTabbed;
import level.editor.view.action.ActionConstants;

public class SaveAction extends FileAction implements PropertyChangeListener,
		ChangeListener
{

	public SaveAction(MainTabbed tabbed)
	{
		super("Save", tabbed, ActionConstants.ICON_DIR + "save.png");
		initiateListeners();
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (tabbed.getSelectedMain() != null)
		{
			Main main = tabbed.getSelectedMain();
			main.save();
			main.setDirty(Main.NOT_DIRTY);
		}
	}

	@Override
	public void propertyChange(PropertyChangeEvent e)
	{
		if (e.getSource() instanceof Main)
		{
			if (((Boolean) ((Main) e.getSource())
					.getClientProperty(Main.DIRTY_PROPERTY)) != null)
			{
				setEnabled(((Boolean) ((Main) e.getSource())
						.getClientProperty(Main.DIRTY_PROPERTY)));
			}
		}
	}

	@Override
	public void stateChanged(ChangeEvent e)
	{
		if (e.getSource() instanceof MainTabbed)
		{
			MainTabbed mainTabbed = (MainTabbed) e.getSource();
			if (mainTabbed.getSelectedMain() != null)
			{
				Main main = mainTabbed.getSelectedMain();
				main.removePropertyChangeListener(this);
				main.addPropertyChangeListener(this);
				if (((Boolean) mainTabbed.getSelectedMain().getClientProperty(
						Main.DIRTY_PROPERTY)) != null)
				{
					setEnabled(((Boolean) mainTabbed.getSelectedMain()
							.getClientProperty(Main.DIRTY_PROPERTY)));
				}
			}
		}
	}

	private void initiateListeners()
	{
		tabbed.addChangeListener(this);
		for (Component component : tabbed.getComponents())
		{
			if (component instanceof MainScroll)
			{
				Main main = (Main) ((MainScroll) component).getMain();
				main.addPropertyChangeListener(this);
			}
		}
	}
}
